<?php
/**
 * 飞书登录 - 保存配置
 */

header('Content-Type: application/json');

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (empty($data['app_id']) || empty($data['app_secret']) || empty($data['redirect_uri'])) {
    echo json_encode(['success' => false, 'message' => '请填写所有必填项']);
    exit;
}

// 读取现有配置
$configFile = __DIR__ . '/../../config.php';
if (!file_exists($configFile)) {
    echo json_encode(['success' => false, 'message' => '配置文件不存在']);
    exit;
}

$config = include $configFile;

// 更新飞书配置
if (!isset($config['plugins']['feishu'])) {
    $config['plugins']['feishu'] = ['enabled' => false];
}

$config['plugins']['feishu']['app_id'] = trim($data['app_id']);
$config['plugins']['feishu']['app_secret'] = trim($data['app_secret']);
$config['plugins']['feishu']['redirect_uri'] = trim($data['redirect_uri']);

// 保存配置
$configContent = "<?php\n/**\n * 氚云API管理系统配置文件\n * Alyr.net 企业级配置管理\n */\n\nreturn " . var_export($config, true) . ";\n";

if (file_put_contents($configFile, $configContent)) {
    echo json_encode(['success' => true, 'message' => '配置保存成功']);
} else {
    echo json_encode(['success' => false, 'message' => '保存配置失败']);
}
